package com.cloudlead.common.worker.web;

import com.cloudlead.common.lang.serialize.*;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spring.scope.RequestContextFilter;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;

import javax.ws.rs.core.MediaType;
import java.sql.Timestamp;
import java.util.Date;

public class WebApplication extends ResourceConfig {

    public WebApplication() {
        register(LoggingFilter.class);
        register(RequestContextFilter.class);
        register(AccessControlContainerResponseFilter.class);
        register(MultiPartFeature.class);

        // 配置Jackson
        JacksonJaxbJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider();
        ObjectMapper objectMapper = jacksonJsonProvider.locateMapper(null,
                MediaType.APPLICATION_JSON_TYPE);
        if (null != objectMapper) {
            // 注册自定义的序列化
            // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
            SimpleModule simpleModole = new SimpleModule("SimpleModule");
            simpleModole.addSerializer(Date.class, new SimpleDateSerializer());
            simpleModole.addSerializer(DateTime.class, new DateTimeSerializer());
            simpleModole.addSerializer(LocalDate.class, new LocalDateSerializer());

            SimpleDateDeserializer dateDeserializer = new SimpleDateDeserializer();
            SimpleTimestampDeserializer timestampDeserializer = new SimpleTimestampDeserializer(
                    dateDeserializer);
            simpleModole.addDeserializer(Timestamp.class, timestampDeserializer);
            simpleModole.addDeserializer(Date.class, dateDeserializer);
            simpleModole.addDeserializer(DateTime.class, new DateTimeDeserializer());
            simpleModole.addDeserializer(LocalDate.class, new LocalDateDeserializer());
            objectMapper.registerModule(simpleModole);
        }
        register(jacksonJsonProvider);
        register(JsonMappingExceptionMapper.class);
        register(JsonParseExceptionMapper.class);
        property("jersey.config.server.wadl.disableWadl", "true");

        register(WebApplicationExceptionMapper.class);
        packages("com.cloudlead.web.resource");

    }

}
